eststo clear

if("`c(os)'"=="Windows"){
	local tableSaveDir = "ReviewResponseResults\"
	local plotSaveDir = "ReviewResponseResults\"
	local pythonSaveDir = "PythonScripts\"
}
else{
	local tableSaveDir = "ReviewResponseResults/"
	local plotSaveDir = "ReviewResponseResults/"
	local pythonSaveDir = "PythonScripts/"
}

//With linear time trends
//Establish Control Variable Sets
local spec1Controls = "c.normYear#i.stateGroup asinhMetroPop asinhNonMetroPop asinhMetroInc asinhNonMetroInc logrealmeangasprice logemployment loglicenseddrivers logrealstategdp logroadmileage"
local spec2Controls = "`spec1Controls' i.transactionDataDummy"
local spec3Controls = "`spec2Controls' i.regDummyExtSpec3"
local spec4Controls = "`spec2Controls' i.regDummyExtSpec4"

//Establish ci level
local ciLevel = 95

//Establish Cluster Variable
local clusterVar = "stateGroup"

//Absorb Vars are always time and state fixed effects
local absorbVars = "ib51.stateGroup ib1995.year"

//Estimate Models
//Estimate Spec. 1 DiD Model
qui reghdfe logregistrations i.nosafetyind `spec1Controls', cluster(`clusterVar') absorb(`absorbVars') res(spec1Res)
eststo spec1
local df = e(N_clust)-1
addRobustFStat 1.nosafetyind
addTreat 1.nosafetyind
estadd local dsc = "None" 
estadd local groupFE = "Y"
estadd local timeFE = "Y"
estadd local timeTrend = "Y"
estadd local commonControls = "Y"
estadd local modelNum = "(1)"
//Estimate Spec. 2 DiD Model 
qui reghdfe logregistrations i.nosafetyind `spec2Controls', cluster(`clusterVar') absorb(`absorbVars') res(spec2Res)
eststo spec2
local df = e(N_clust)-1
addRobustFStat 1.nosafetyind
addTreat 1.nosafetyind
estadd local dsc = "Documented" 
estadd local groupFE = "Y"
estadd local timeFE = "Y"
estadd local timeTrend = "Y"
estadd local commonControls = "Y"
estadd local modelNum = "(2)"
//Estimate Spec. 3 DiD Model
qui reghdfe logregistrations i.nosafetyind `spec3Controls', cluster(`clusterVar') absorb(`absorbVars') res(spec3Res)
eststo spec3
local df = e(N_clust)-1
addRobustFStat 1.nosafetyind
addTreat 1.nosafetyind
estadd local dsc = "\makecell{Large \nextline Undocumented}" 
estadd local groupFE = "Y"
estadd local timeFE = "Y"
estadd local timeTrend = "Y"
estadd local commonControls = "Y"
estadd local modelNum = "(3)"
//Estimate Spec. 4 Model
qui reghdfe logregistrations i.nosafetyind `spec4Controls', cluster(`clusterVar') absorb(`absorbVars') res(spec4Res)
eststo spec4
local df = e(N_clust)-1
addRobustFStat 1.nosafetyind
addTreat 1.nosafetyind
estadd local dsc = "\makecell{Small \nextline Undocumented}" 
estadd local groupFE = "Y"
estadd local timeFE = "Y"
estadd local timeTrend = "Y"
estadd local commonControls = "Y"
estadd local modelNum = "(4)"

//Plot residuals in python
python script "`pythonSaveDir'plotResiduals.py"

//Export Model Results to TeX Files
//Establish Format
local fmtDiD = `"drop(*) nocon label compress starlevels(* 0.1 ** 0.05 *** 0.01) nodepvar nomtitle nonumbers not nostar noline"'


local noteString = "\hline \hline \end{tabular} \vspace{0.2cm} \begin{tablenotes} \begin{spacing}{0} \begin{footnotesize} \item \textbf{Notes:} This table presents difference-in-differences estimates of the impact of the removal of safety inspections on the log of vehicle registrations.  The unit of observation is state-year. The four specifications pertaining to different levels of ``Data Source Controls'' (DSCs) and control specifications are documented in Table \cref{ssec:Spec}. Standard errors, reported in parentheses, are clustered by state. * p\textless 0.1, ** p\textless 0.05, *** p\textless 0.01 \end{footnotesize} \end{spacing} \end{tablenotes} \end{table}"

//Export Table
esttab spec1 spec2 spec3 spec4 using "`tableSaveDir'RegDiD.tex", `fmtDiD' title("Diff-in-Diff Results \label{tab:RegDiD}") stats(modelNum treatb treatse dsc groupFE timeFE timeTrend commonControls fStat N r2, labels("\hline \hline \multicolumn{5}{c}{Dep. Var.: Log Number of Vehicle Registrations} \\ " "Removal of" "Safety Inspections" "\makecell[l]{Data Source \nextline Controls}" "State Fixed Effects" "Year Fixed Effects" "\makecell[l]{State-Specific Linear \\ Time Trends}" "Common Controls" "Robust F-Stat" "Number of Obs." "R\textsuperscript{2}")fmt(%8.3f %8.3f %8.3f %8.3f  %8.3f  %8.3f  %8.3f  %8.3f %8.3f %8.0fc %8.3f)) replace postfoot("`noteString'")


//Estimate per-Capita Models
//Establish Control Variable Sets
local spec1PerCapitaControls = "ib51.stateGroup ib1995.year c.normYear#i.stateGroup asinhMetroPop asinhNonMetroPop asinhMetroInc asinhNonMetroInc logrealmeangasprice logemployment loglicenseddrivers logrealstategdp logroadmileage"
local spec2PerCapitaControls = "`spec1Controls' i.transactionDataDummy"
local spec3PerCapitaControls = "`spec2Controls' i.regPerCapitaDummyExtSpec3"
local spec4PerCapitaControls = "`spec2Controls' i.regPerCapitaDummyExtSpec4"

//Estimate Spec. 1 DiD Model
qui reghdfe logRegPerCapita i.nosafetyind `spec1PerCapitaControls', cluster(`clusterVar') absorb(`absorbVars') res(spec1PerCapitaRes)
eststo spec1PerCapita
local df = e(N_clust)-1
addRobustFStat 1.nosafetyind
addTreat 1.nosafetyind
estadd local dsc = "None" 
estadd local groupFE = "Y"
estadd local timeFE = "Y"
estadd local timeTrend = "Y"
estadd local commonControls = "Y"
estadd local modelNum = "(1)"
//Estimate Spec. 2 DiD Model 
qui reghdfe logRegPerCapita i.nosafetyind `spec2PerCapitaControls', cluster(`clusterVar') absorb(`absorbVars') res(spec2PerCapitaRes)
eststo spec2PerCapita
local df = e(N_clust)-1
addRobustFStat 1.nosafetyind
addTreat 1.nosafetyind
estadd local dsc = "Documented" 
estadd local groupFE = "Y"
estadd local timeFE = "Y"
estadd local timeTrend = "Y"
estadd local commonControls = "Y"
estadd local modelNum = "(2)"
//Estimate Spec. 3 DiD Model
qui reghdfe logRegPerCapita i.nosafetyind `spec3PerCapitaControls', cluster(`clusterVar') absorb(`absorbVars') res(spec3PerCapitaRes)
eststo spec3PerCapita
local df = e(N_clust)-1
addRobustFStat 1.nosafetyind
addTreat 1.nosafetyind
estadd local dsc = "\makecell{Large \nextline Undocumented}" 
estadd local groupFE = "Y"
estadd local timeFE = "Y"
estadd local timeTrend = "Y"
estadd local commonControls = "Y"
estadd local modelNum = "(3)"
//Estimate Spec. 4 Model
qui reghdfe logRegPerCapita i.nosafetyind `spec4PerCapitaControls', cluster(`clusterVar') absorb(`absorbVars') res(spec4PerCapitaRes)
eststo spec4PerCapita
local df = e(N_clust)-1
addRobustFStat 1.nosafetyind
addTreat 1.nosafetyind
estadd local dsc = "\makecell{Small \nextline Undocumented}" 
estadd local groupFE = "Y"
estadd local timeFE = "Y"
estadd local timeTrend = "Y"
estadd local modelNum = "(4)"


local noteString = "\hline \hline \end{tabular} \vspace{0.2cm} \begin{tablenotes} \begin{spacing}{0} \begin{footnotesize} \item \textbf{Notes:} This table presents difference-in-differences estimates of the impact of the removal of safety inspections on the log of vehicle registrations per capita.  The unit of observation is state-year. The four specifications pertaining to different levels of ``Data Source Controls'' (DSCs) and control specifications are documented in Table \cref{ssec:Spec}. Standard errors, reported in parentheses, are clustered by state. * p\textless 0.1, ** p\textless 0.05, *** p\textless 0.01 \end{footnotesize} \end{spacing} \end{tablenotes} \end{table}"

//Export Table
esttab spec1PerCapita spec2PerCapita spec3PerCapita spec4PerCapita using "`tableSaveDir'RegPerCapitaDiD.tex", `fmtDiD' title("Per-Capita Diff-in-Diff Results \label{tab:RegPerCapitaDiD}") stats(modelNum treatb treatse dsc groupFE timeFE timeTrend commonControls fStat N r2, labels("\hline \hline \multicolumn{5}{c}{Dep. Var.: Log Number of Vehicle Registrations} \\ " "Removal of" "Safety Inspections" "\makecell[l]{Data Source \nextline Controls}" "State Fixed Effects" "Year Fixed Effects" "\makecell[l]{State-Specific Linear \\ Time Trends}" "Common Controls" "Robust F-Stat" "Number of Obs." "R\textsuperscript{2}")fmt(%8.3f %8.3f %8.3f %8.3f  %8.3f  %8.3f  %8.3f  %8.3f %8.3f %8.0fc %8.3f)) replace postfoot("`noteString'")


//Set looRun to 1 to re-estimate leave-one-out analysis, 0 to skip the analysis
local looRun = 1
if(`looRun'==1){
	
if("`c(os)'"=="Windows"){
	local tableSaveDir = "Tables\"
	local plotSaveDir = "Plots\"
	local pythonSaveDir = "PythonScripts\"
}
else{
	local tableSaveDir = "Tables/"
	local plotSaveDir = "Plots/"
	local pythonSaveDir = "PythonScripts/"
}
	
//Run LOO Analysis
//Under Specification 1
qui putexcel set "`tableSaveDir'did.xlsx", sheet("LOO-Spec1", replace) modify
qui putexcel A1 = "State Removed"
qui putexcel B1 = "Eta"
qui putexcel C1 = "Eta Std. Err."
qui putexcel D1 = "P-Val(Eta=0)"
qui levelsof statecode

local index = 2
foreach tempSC in `r(levels)'{
	di "Working on DiD LOO-Spec1 w/o `tempSC'"
	qui reghdfe logregistrations i.nosafetyind `spec1Controls' if statecode != "`tempSC'", cluster(`clusterVar') absorb(`absorbVars')
	local b = _b[1.nosafetyind]
	local bse = _se[1.nosafetyind]
	qui test 1.nosafetyind
	local pVal = `r(p)'
	
	qui putexcel A`index' = "`tempSC'"
	qui putexcel B`index' = `b'
	qui putexcel C`index' = `bse'
	qui putexcel D`index' = `pVal'
	
	local index=`index'+1
}
//Under Specification 2
qui putexcel set "`tableSaveDir'did.xlsx", sheet("LOO-Spec2", replace) modify
qui putexcel A1 = "State Removed"
qui putexcel B1 = "Eta"
qui putexcel C1 = "Eta Std. Err."
qui putexcel D1 = "P-Val(Eta=0)"
qui levelsof statecode

local index = 2
foreach tempSC in `r(levels)'{
	di "Working on DiD LOO-Spec2 w/o `tempSC'"
	qui reghdfe logregistrations i.nosafetyind `spec2Controls' if statecode != "`tempSC'", cluster(`clusterVar') absorb(`absorbVars')
	local b = _b[1.nosafetyind]
	local bse = _se[1.nosafetyind]
	qui test 1.nosafetyind
	local pVal = `r(p)'
	
	qui putexcel A`index' = "`tempSC'"
	qui putexcel B`index' = `b'
	qui putexcel C`index' = `bse'
	qui putexcel D`index' = `pVal'
	
	local index=`index'+1
}

//Under Specification 3
qui putexcel set "`tableSaveDir'did.xlsx", sheet("LOO-Spec3", replace) modify
qui putexcel A1 = "State Removed"
qui putexcel B1 = "Eta"
qui putexcel C1 = "Eta Std. Err."
qui putexcel D1 = "P-Val(Eta=0)"
qui levelsof statecode

local index = 2
foreach tempSC in `r(levels)'{
	di "Working on DiD LOO-Spec3 w/o `tempSC'"
	qui reghdfe logregistrations i.nosafetyind `spec3Controls' if statecode != "`tempSC'", cluster(`clusterVar') absorb(`absorbVars')
	local b = _b[1.nosafetyind]
	local bse = _se[1.nosafetyind]
	qui test 1.nosafetyind
	local pVal = `r(p)'
	
	qui putexcel A`index' = "`tempSC'"
	qui putexcel B`index' = `b'
	qui putexcel C`index' = `bse'
	qui putexcel D`index' = `pVal'
	
	local index=`index'+1
}

//Under Specification 4
qui putexcel set "`tableSaveDir'did.xlsx", sheet("LOO-Spec4", replace) modify
qui putexcel A1 = "State Removed"
qui putexcel B1 = "Eta"
qui putexcel C1 = "Eta Std. Err."
qui putexcel D1 = "P-Val(Eta=0)"
qui levelsof statecode

local index = 2
foreach tempSC in `r(levels)'{
	di "Working on DiD LOO-Spec4 w/o `tempSC'"
	qui reghdfe logregistrations i.nosafetyind `spec4Controls' if statecode != "`tempSC'", cluster(`clusterVar') absorb(`absorbVars')
	local b = _b[1.nosafetyind]
	local bse = _se[1.nosafetyind]
	qui test 1.nosafetyind
	local pVal = `r(p)'
	
	qui putexcel A`index' = "`tempSC'"
	qui putexcel B`index' = `b'
	qui putexcel C`index' = `bse'
	qui putexcel D`index' = `pVal'
	
	local index=`index'+1
}
	
}




//Without linear time trends
//Establish Control Variable Sets
local spec1Controls = "ib51.stateGroup ib1995.year asinhMetroPop asinhNonMetroPop asinhMetroInc asinhNonMetroInc logrealmeangasprice logemployment loglicenseddrivers logrealstategdp logroadmileage"
local spec2Controls = "`spec1Controls' i.transactionDataDummy"
local spec3Controls = "`spec2Controls' i.regDummyExtSpec3"
local spec4Controls = "`spec2Controls' i.regDummyExtSpec4"


//Establish ci level
local ciLevel = 95

//Establish Cluster Variable
local clusterVar = "stateGroup"

//Absorb Vars are always time and state fixed effects
local absorbVars = "ib51.stateGroup ib1995.year"

//Estimate Models
//Estimate Spec. 1 DiD Model
qui reghdfe logregistrations i.nosafetyind `spec1Controls', cluster(`clusterVar') absorb(`absorbVars') res(spec1ResWoTT)
eststo spec1WoTT
local df = e(N_clust)-1
addRobustFStat 1.nosafetyind
addTreat 1.nosafetyind
estadd local dsc = "None" 
estadd local groupFE = "Y"
estadd local timeFE = "Y"
estadd local timeTrend = "N"
estadd local commonControls = "Y"
estadd local modelNum = "(1)"
//Estimate Spec. 2 DiD Model 
qui reghdfe logregistrations i.nosafetyind `spec2Controls', cluster(`clusterVar') absorb(`absorbVars') res(spec2ResWoTT)
eststo spec2WoTT
local df = e(N_clust)-1
addRobustFStat 1.nosafetyind
addTreat 1.nosafetyind
estadd local dsc = "Documented" 
estadd local groupFE = "Y"
estadd local timeFE = "Y"
estadd local timeTrend = "N"
estadd local commonControls = "Y"
estadd local modelNum = "(2)"
//Estimate Spec. 3 DiD Model
qui reghdfe logregistrations i.nosafetyind `spec3Controls', cluster(`clusterVar') absorb(`absorbVars') res(spec3ResWoTT)
eststo spec3WoTT
local df = e(N_clust)-1
addRobustFStat 1.nosafetyind
addTreat 1.nosafetyind
estadd local dsc = "\makecell{Large \nextline Undocumented}" 
estadd local groupFE = "Y"
estadd local timeFE = "Y"
estadd local timeTrend = "N"
estadd local commonControls = "Y"
estadd local modelNum = "(3)"
//Estimate Spec. 4 Model
qui reghdfe logregistrations i.nosafetyind `spec4Controls', cluster(`clusterVar') absorb(`absorbVars') res(spec4ResWoTT)
eststo spec4WoTT
local df = e(N_clust)-1
addRobustFStat 1.nosafetyind
addTreat 1.nosafetyind
estadd local dsc = "\makecell{Small \nextline Undocumented}" 
estadd local groupFE = "Y"
estadd local timeFE = "Y"
estadd local timeTrend = "N"
estadd local commonControls = "Y"
estadd local modelNum = "(4)"

//Plot residuals in python
python script "`pythonSaveDir'plotResiduals.py"

//Export Model Results to TeX Files
//Establish Format


local noteString = "\hline \hline \end{tabular} \vspace{0.2cm} \begin{tablenotes} \begin{spacing}{0} \begin{footnotesize} \item \textbf{Notes:} This table presents difference-in-differences estimates of the impact of the removal of safety inspections on the log of vehicle registrations. The unit of observation is state-year. The four specifications pertaining to different levels of ``Data Source Controls'' (DSCs) and control specifications are documented in Table \cref{ssec:Spec}. Standard errors, reported in parentheses, are clustered by state. * p\textless 0.1, ** p\textless 0.05, *** p\textless 0.01 \end{footnotesize} \end{spacing} \end{tablenotes} \end{table}"

//Export Table
esttab spec1WoTT spec2WoTT spec3WoTT spec4WoTT using "`tableSaveDir'RegDiDWoTT.tex", `fmtDiD' title("Diff-in-Diff Results without Time Trends \label{tab:RegDiDWoTT}") stats(modelNum treatb treatse dsc groupFE timeFE timeTrend commonControls fStat N r2, labels("\hline \hline \multicolumn{5}{c}{Dep. Var.: Log Number of Vehicle Registrations} \\ " "Removal of" "Safety Inspections" "\makecell[l]{Data Source \nextline Controls}" "State Fixed Effects" "Year Fixed Effects" "\makecell[l]{State-Specific Linear \\ Time Trends}" "Common Controls" "Robust F-Stat" "Number of Obs." "R\textsuperscript{2}")fmt(%8.3f %8.3f %8.3f %8.3f  %8.3f  %8.3f  %8.3f  %8.3f %8.3f %8.0fc %8.3f)) replace postfoot("`noteString'")
